package com.hyphenate.easeui.utils;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.widget.ImageView;
import android.widget.TextView;
import app.twotiger.p2p.R;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.hyphenate.easeui.controller.EaseUI;
import com.hyphenate.easeui.controller.EaseUI.EaseUserProfileProvider;
import com.hyphenate.easeui.domain.EaseUser;
import com.twotiger.and.TwoTigerApp;
import com.twotiger.and.util.PreferencesUtils;
import com.twotiger.and.util.StringUtils;

public class EaseUserUtils {

    static EaseUserProfileProvider userProvider;

    private static Context mContext;

    static {
        userProvider = EaseUI.getInstance().getUserProfileProvider();
        mContext = TwoTigerApp.getInstance();
    }

    /**
     * 根据username获取相应user
     * @param username
     * @return
     */
    public static EaseUser getUserInfo(String username) {
        if (!StringUtils.isEmpty(PreferencesUtils.getString(mContext, username))) {
            try {
                JSONObject agentInfo = new JSONObject(PreferencesUtils.getString(mContext, username));
                EaseUser user = new EaseUser(username);
                if(!StringUtils.isEmpty(agentInfo.getString("avatar"))){
                    user.setAvatar("http:" + agentInfo.getString("avatar"));
                }
                user.setNick(agentInfo.getString("userNickname"));
                return user;
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        if (userProvider != null)
            return userProvider.getUser(username);

        return null;
    }

    /**
     * 设置用户头像
     * @param username
     */
    public static void setUserAvatar(Context context, String username, ImageView imageView) {
        EaseUser user = getUserInfo(username);
        if (user != null && user.getAvatar() != null) {
            try {
                int avatarResId = Integer.parseInt(user.getAvatar());
                Glide.with(context).load(avatarResId).into(imageView);
            } catch (Exception e) {
                //正常的string路径
                Glide.with(context).load(user.getAvatar()).diskCacheStrategy(DiskCacheStrategy.ALL)
                    .placeholder(R.drawable.logo).into(imageView);
            }
        } else {
            Glide.with(context).load(R.drawable.logo).into(imageView);
        }
    }

    /**
     * 设置用户昵称
     */
    public static void setUserNick(String username, TextView textView) {
        if (textView != null) {
            EaseUser user = getUserInfo(username);
            if (user != null && user.getNick() != null) {
                textView.setText(user.getNick());
            } else {
                textView.setText(username);
            }
        }
    }

}
